package com.corner.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.avos.avoscloud.AVAnalytics;
import com.corner.R;
import com.corner.app.App;
import com.corner.app.ConsTants;
import com.corner.model.cornerservice.domain.CloudFile;
import com.corner.model.cornerservice.domain.User;
import com.corner.model.cornerservice.helper.SendInfoTask;
import com.corner.model.cornerservice.helper.UserHelper;
import com.corner.model.leancloud.helper.MessageHelperV2;
import com.corner.model.oss.OSSManager;
import com.corner.presenter.imp.MainPresenter;
import com.corner.ui.base.BaseActivity;
import com.corner.ui.fragment.LocationListFragment;
import com.corner.ui.fragment.MineFragment;
import com.corner.ui.fragment.SessionFragment;
import com.corner.ui.view.IMainView;
import com.corner.utils.MyCrashHandler;
import com.corner.utils.NotificationUtil;
import com.corner.utils.view.FindView;
import com.corner.utils.view.MainActionBar;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * MainActivity
 * 主页 。
 */
public class MainActivity extends BaseActivity<MainPresenter> implements
        OnCheckedChangeListener, OnClickListener, IMainView {
    @FindView(R.id.ll_root)
    public LinearLayout llRoot;
    public MainActionBar actionBar;
    @FindView(R.id.rg_main_bottom)
    private RadioGroup rgBottom;
    @FindView(R.id.rb_session)
    private RadioButton rbSession;
    @FindView(R.id.rb_mine)
    private RadioButton rbMine;
    @FindView(R.id.rb_location)
    private RadioButton rbLocation;
    @FindView(R.id.frag_pager)
    private ViewPager fragPager;
    private FragmentPagerAdapter adapter;
    private List<Fragment> fragments;
    /**
     * 当前正在展示fragment的索引
     */
    private int location;

    private boolean isInstallationIdSave;
    private String nickName;
    private long lastTimeMineClick;
    private long lastTimeLocationClick;


    @Override
    protected MainPresenter createP() {
        return new MainPresenter();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        savedInstanceState = null;
        App.application.initSDFile();
        super.onCreate(savedInstanceState);
        // 如果你想跟踪统计应用的打开情况，添加下列代码到你的主 Activity 的 onCreate 方法：
        AVAnalytics.trackAppOpened(getIntent());
    }

    @Override
    public void initView() {
        super.initView();

        actionBar = new MainActionBar(this);

        location = 0;
        initActionBar(location);
        if (fragments == null) {
            fragments = new ArrayList<Fragment>();
            fragments.add(new LocationListFragment());
            fragments.add(new SessionFragment());
            fragments.add(new MineFragment());
        }
        adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public Fragment getItem(int location) {
                return fragments.get(location);
            }
        };
        fragPager.setAdapter(adapter);

        fragPager.setOffscreenPageLimit(3);


    }


    @Override
    protected void onNetStatusChanged(boolean isConnected) {
        super.onNetStatusChanged(isConnected);
        if (isConnected) {
            saveInstallationId();
            uploadLog();
        }
    }

    /**
     * 上传日志
     */
    private void uploadLog() {
        final File logTxt = new File(Environment.getExternalStorageDirectory(), MyCrashHandler.MY_LOG_TXT);
        if (logTxt.exists()) {
            try {
                OSSManager.upload(logTxt.getAbsolutePath(), String.valueOf("logs/"+(logTxt.getAbsolutePath() + System.currentTimeMillis()).hashCode() + ".log"), new OSSManager.SaveCallback() {
                    @Override
                    public void onSuccess(CloudFile cloudFile) {
                        logTxt.delete();
                    }

                    @Override
                    public void onProgress(String objectKey, int byteCount, int totalSize) {
                    }

                    @Override
                    public void onFailure(Throwable throwable) {
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void initData() {
        App.application.initSession();
        MessageHelperV2.openImClient();
        saveInstallationId();
        UserHelper.saveUser(User.getCurrentUser().getObjectId());
    }

    @Override
    protected void onResume() {
        super.onResume();
        NotificationUtil.cancleNotify(App.application, ConsTants.MESSAGE_NOTIFY);
        SendInfoTask.getInstance().excuteTask();
    }

    /**
     * 保存推送的Id
     */
    private void saveInstallationId() {
        if (isInstallationIdSave) {
            return;
        }
        presenter.saveInstallationId();
    }


    @Override
    protected void setOnClick() {
        rgBottom.setOnCheckedChangeListener(this);
        actionBar.btnLeft.setOnClickListener(this);
        actionBar.btnRight.setOnClickListener(this);
        actionBar.ivRight.setOnClickListener(this);

        rbMine.setOnClickListener(this);
        rbLocation.setOnClickListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_location:
                fragPager.setCurrentItem(0, false);
                location = 0;
                break;
            case R.id.rb_mine:
                fragPager.setCurrentItem(2, false);
                location = 2;
                break;
            case R.id.rb_session:
                fragPager.setCurrentItem(1, false);
                location = 1;
                break;
        }
        initActionBar(location);
    }

    private void initActionBar(int location) {
        switch (location) {
            case 0:
                actionBar.initActionBarButton();
                actionBar.ivRight.setVisibility(View.VISIBLE);
                actionBar.btnLeft.setVisibility(View.VISIBLE);
                actionBar.ivRight.setImageResource(R.drawable.location_create_info);
                actionBar.btnLeft.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                actionBar.btnLeft.setText(getString(R.string.frag_location_list_action_bar_attention));
                actionBar.btnLeft.setTextColor(getResources().getColor(R.color.common_blue));

                actionBar.tvMiddle.setText(getString(R.string.main_activity_action_bar_left_home));
                actionBar.tvMiddle.setTextColor(getResources().getColor(R.color.text_black));
                break;
            case 1:
                actionBar.initActionBarButton();
                actionBar.tvMiddle.setText(getString(R.string.main_activity_action_bar_left_message));
                actionBar.tvMiddle.setTextColor(getResources().getColor(R.color.text_black));
                break;
            case 2:
                actionBar.initActionBarButton();
                actionBar.ivRight.setVisibility(View.VISIBLE);
                actionBar.ivRight.setImageResource(R.drawable.mine_plus_set);
                if (TextUtils.isEmpty(nickName)) {
                    actionBar.tvMiddle.setTextColor(getResources().getColor(R.color.text_black));
                    actionBar.tvMiddle.setText(getString(R.string.main_activity_action_bar_left_mine));
                } else {
                    actionBar.tvMiddle.setTextColor(getResources().getColor(R.color.common_blue));
                    actionBar.tvMiddle.setText(nickName);
                }
                break;
        }
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_actionbar_left:
                switch (location) {
                    case 0:
                        // 此时是查看关注的
                        seeAttention();
                        break;
                }
                break;
            case R.id.rb_mine:
                long currTime = SystemClock.uptimeMillis();
                if (currTime - lastTimeMineClick < 1000) {
                    ((MineFragment) (fragments.get(2))).upToRefresh();
                }
                lastTimeMineClick = currTime;
                break;
            case R.id.rb_location:
                currTime = SystemClock.uptimeMillis();
                if (currTime - lastTimeLocationClick < 1000) {
                    ((LocationListFragment) (fragments.get(0))).upToRefresh();
                }
                lastTimeLocationClick = currTime;
                break;
            case R.id.iv_actionbar_right:
                switch (location) {
                    case 0:
                        createInfoWithLocation();
                        break;
                    case 2:
                        Intent intent = new Intent(this, UserSettingActivity.class);
                        startActivity(intent);
                        break;
                }
                break;
        }
    }


    /**
     * 跳转到发送Info的页面
     */
    private void createInfoWithLocation() {
        Intent intent = new Intent(this, CreateInfoActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.in_bottom, R.anim.anim_none);
    }

    /**
     * 跳转到我关注的页面
     */
    private void seeAttention() {
        Intent intent = new Intent(this, AttentionActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.fragment_slide_in_left, R.anim.fragment_slide_out_right);
    }


    /**
     * 设置是否已读
     *
     * @param b
     */
    public void setMessageNotReaded(boolean b) {
        if (b) {
            rbSession.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.rb_session_new_message_bg, 0, 0);
        } else {
            rbSession.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.rb_session_bg, 0, 0);
        }
    }

    @Override
    public void saveInstallationIdError() {
        isInstallationIdSave = false;
    }

    @Override
    public void saveInstallationIdSucess() {
        isInstallationIdSave = true;
    }


    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }


    public void setNickName(String nickName) {
        this.nickName = nickName;
        if (location == 2) {
            actionBar.tvMiddle.setText(nickName);
        }
    }
}